#include "blisp.h"
#include "interp_priv.h"

static Token Tk_None, Tk_EoI;

void Interp_init(void)
{
/* TODO */
}

static void Lexer_init(void)
{
/* TODO */
}

static Lexer *Lexer_new(void)
{
	Lexer *lexer;
	
	/* Initialize lexer */
	lexer = GC_NEW(Lexer);
	if (lexer == NULL) return NULL;
	/*
	 * Boehm GC automatically zeroes out memory,
	 * so I won't bother init'ing everything to zero.  :P
	 */

	lexer->outbuf = GC_MALLOC_ATOMIC(BUFSIZ);
	lexer->outbuf_end = lexer->outbuf;
	lexer->inbuf = GC_MALLOC_ATOMIC(BUFSIZ);
	lexer->inbuf_start = lexer->inbuf;
	lexer->inbuf_end = lexer->inbuf;

	return lexer;
}

/*
static int Lexer_feedFilePtr(Lexer *lexer, FILE *file)
{
return EXIT_FAILURE; /=* TODO *=/
}

static int Lexer_feedFileName(Lexer *lexer, char *file_name)
{
return EXIT_FAILURE; /=* TODO *=/
}
*/

static void Lexer_feedChars(Lexer *lexer, char *chars, int len)
{
	if (lexer == NULL || chars == NULL || len <= 0) return;

	lexer->inbuf_cur = lexer->inbuf_end;
	memcpy(lexer->inbuf_cur, chars, len);
	lexer->inbuf_end += len;
}

/* static void Lexer_push(Lexer *lexer, char *chars, int len); */

/* turned into macro */
/*
static int Lexer_hasNext(Lexer *lexer)
{
	return lexer != NULL && lexer->inbuf_start < lexer->inbuf_end;
}
*/

static Token *Lexer_next(Lexer *lexer)
{
	if (lexer == NULL) return &Tk_None;
	if (!lexer_hasNext(lexer)) return &Tk_EoI;

comment_string:
	while (lexer->comment || lexer->string)
		lexer_readChar(lexer);

end:
	return NULL;/* TODO */
}

static int lexer_readChar(Lexer *lexer)
{
	char c;

	if (!lexer_hasNextNotNull(lexer)) return EOF;

	c = *lexer->inbuf_start;
	lexer->inbuf_start++;

	lexer->char_abs++;
	if (c == '\n')
	{
		lexer->col = 0;
		lexer->line++;
		lexer->comment = CFALSE;
	}
	else
	{
		lexer->col++;
		
		switch (c)
		{
		/* if string delimiter, switch string flag */
		case STRING_DELIM: lexer->string = !lexer->string; break;

		case COMMENT_DELIM: lexer->comment = CTRUE; break;

		default:
		if (lexer->string || !isspace(c))
			lexer_outBufferAppend(lexer, c);
		}
	}

	return c;
}
